<div class="open-form">
  <div class="open-model">
    <div class="open-auto">
      <!-- 头部操作栏 -->
      <div class="layui-form toolbar">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label w-auto">名称：</label>
            <div class="layui-input-inline mr0">
              <input name="name" class="layui-input" type="text" placeholder="请输入名称" />
            </div>
          </div>
          <div class="layui-inline">
            <button class="layui-btn icon-btn" lay-filter="specTableFormSubSearchLog" lay-submit layui-form-keyDownSearch="true"><i class="layui-icon">&#xe615;</i>搜索</button>
            <button id="productSpecBtnAdd" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
            <button id="productSpecBtnDel" class="layui-btn icon-btn layui-btn-danger"><i class="layui-icon"></i>批量删除</button>
          </div>
        </div>
      </div>
      <!-- 表格 -->
      <table class="layui-table" id="productSpecTable" lay-filter="productSpecTable"></table>
    </div>
    <div class="layui-form-item text-right">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
    </div>
  </div>
</div>

<script type="text/html" id="productSpecTableBar">
  <a class="layui-btn layui-btn-warm layui-btn-xs" lay-event="editSpec">修改</a>
  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="productSpecForm">
  <form lay-filter="productSpecForm" class="layui-form model-form form-scroll">
    <div class="open-details-box pd-20">
      <input name="id" type="hidden" />
      <div class="layui-col-xs6">
        <div class="layui-form-item" style="padding-top: 20px !important;">
          <label class="layui-form-label">物料类别</label>
          <div class="layui-input-block">
            <select name="productTypeId" lay-filter="productTypeId" lay-search lay-verify="required" disabled></select>
            <!-- <input name="parentId" type="hidden" />
                        <div class="layui-input-block" id="selectParentType"></div> -->
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item" style="padding-top: 20px !important;">
          <label class="layui-form-label">规格名称</label>
          <div class="layui-input-block">
            <input name="specName" placeholder="请输入规格名称" type="text" class="layui-input" lay-verify="required" required />
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item">
          <label class="layui-form-label">规格头</label>
          <div class="layui-input-block">
            <input name="specHead" type="text" class="layui-input" lay-verify="required" required />
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item">
          <label class="layui-form-label">引入规格码</label>
          <div class="layui-input-block">
            <select name="specCode" lay-filter="style">
              <option value="is">引入规格码</option>
              <option value="no">不引入规格码中</option>
            </select>
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item">
          <label class="layui-form-label">规格补位位置</label>
          <div class="layui-input-block">
            <select name="specLocation" lay-filter="style">
              <option value="before">前置</option>
              <option value="last">后置</option>
            </select>
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item">
          <label class="layui-form-label">规格参数排序</label>
          <div class="layui-input-block">
            <input name="specSort" type="text" class="layui-input" lay-verify="required" required />
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item">
          <label class="layui-form-label">排序</label>
          <div class="layui-input-block">
            <input name="sortNumber" placeholder="请输入排序" type="text" class="layui-input" lay-verify="" required />
          </div>
        </div>
      </div>

      <div class="layui-col-xs6">
        <div class="layui-form-item">
          <label class="layui-form-label">规格属性</label>
          <div class="layui-input-block">
            <select name="style" lay-filter="style" lay-verify="required" required>
              <option value="">请选择规格属性</option>
              <option value="text">文本</option>
              <option value="single">固定选择项</option>
            </select>
          </div>
        </div>
      </div>

      <div class="layui-form-item" id="btnAddDiv">
        <label class="layui-form-label"></label>
        <div class="layui-input-inline">
          <button id="btnAdd" class="layui-btn" lay-filter="btnAdd" onclick="return false;">添加规格值</button>
        </div>
      </div>

      <div class="layui-col-xs12">
        <div class="layui-form-item">
          <label class="layui-form-label">描述</label>
          <div class="layui-input-block">
            <textarea name="remark" placeholder="请输入描述" class="layui-textarea" />
          </div>
        </div>
      </div>
    </div>
    <div class="layui-form-item text-right pd-20">
      <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
      <button class="layui-btn" lay-filter="productSpecFormSubmit" lay-submit>保存</button>
    </div>
  </form>
</script>

<!-- js部分 -->
<script>
  layui.use(["layer", "form", "table", "laydate", "admin", "laytpl", "tableTreeDj", "config"], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var laydate = layui.laydate;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    var tableTree = layui.tableTreeDj;

    // 回显计量单位数据
    var data = admin.getTempData("data");

    // 渲染表格
    var insTb = table.render({
      elem: "#productSpecTable",
      url: config.base + "enterprise/product/admin/productSpec/list?productType=" + data.id,
      page: true,
      cellMinWidth: 100,
      cols: [
        [
          { type: "checkbox" },
          { type: "numbers", title: "序号" },
          { field: "name", align: "center", title: "规格名称", width: 160 },
          { field: "productTypeName", align: "center", title: "物料类别" },
          { field: "specValues", align: "center", title: "规格值" },
          { field: "specHead", align: "center", title: "规格头" },
          { field: "specCodeDesc", align: "center", title: "引入规格码" },
          { field: "specLocationDesc", align: "center", title: "规格补位位置" },
          { field: "specSort", align: "center", title: "规格参数排序" },
          // , {field: 'sortNumber', align: 'center', title: '排序'}
          { field: "createTime", align: "center", title: "创建时间", width: 160 },
          { align: "center", toolbar: "#productSpecTableBar", title: "操作", width: 150 }
        ]
      ],
      done: function (res, curr, count) {}
    });

    // 工具条点击事件
    table.on("tool(productSpecTable)", function (obj) {
      var data = obj.data;
      if (obj.event === "editSpec") {
        //修改
        data.eventType = "editSpec";
        showEditSpecModel(data);
      } else if (obj.event === "del") {
        // 删除
        doDelete(obj);
      }
    });

    function doDelete(obj) {
      layer.confirm(
        "确定要删除吗？",
        {
          offset: "265px",
          skin: "layui-layer-admin"
        },
        function (i) {
          layer.close(i);
          layer.load(2);
          admin.req(
            "enterprise/product/admin/productSpec/" + obj.data.id,
            {},
            function (res) {
              layer.closeAll("loading");
              if (res.code == 200) {
                layer.msg(res.msg, { icon: 1 });
                obj.del();
                table.reload("productSpecTable");
              } else {
                layer.msg(res.msg, { icon: 2 });
              }
            },
            "DELETE"
          );
        }
      );
    }

    //监听排序
    table.on("sort(productSpecTable)", function (obj) {
      table.reload("productSpecTable", {
        initSort: obj,
        where: {
          sort: obj.field,
          order: obj.type
        }
      });
    });

    // 搜索
    form.on("submit(specTableFormSubSearchLog)", function (data) {
      insTb.reload({ where: data.field, page: { curr: 1 } }, "data");
    });

    // 添加按钮点击事件
    $("#productSpecBtnAdd").click(function () {
      data.eventType = "addSpecFromSpecTable";
      showEditSpecModel(data);
    });

    $("#productSpecBtnDel").click(function () {
      var checkRows = table.checkStatus("productSpecTable");
      if (checkRows.data.length == 0) {
        layer.msg("请选择要删除的数据", { icon: 2 });
      } else {
        var ids = "";
        checkRows.data.forEach((item) => {
          ids += item.id + ",";
        });
        delBatch(ids);
      }
    });

    function delBatch(ids) {
      admin.req(
        "enterprise/product/admin/productSpec/delBatch",
        { ids: ids },
        function (res) {
          if (res.code == 200) {
            layer.msg(res.msg, { icon: 1 });
            table.reload("productSpecTable");
          } else {
            layer.msg(res.msg, { icon: 2 });
          }
        },
        "POST"
      );
    }

    function showEditSpecModel(data) {
      var openIndex = admin.open({
        type: 1,
        area: ["840px", "560px"],
        offset: "130px",
        title: data && (data.eventType == "addSpec" || data.eventType == "addSpecFromSpecTable") ? "添加物料规格值" : "修改物料规格值",
        content: $("#productSpecForm").html(),
        success: function () {
          var productTypeName = "";
          if (data && data.eventType == "editSpec") {
            productTypeName = data.productTypeName;
            data.specName = data.name;
          } else {
            productTypeName = data.name;
          }
          // 去除字符串里的所有标签
          productTypeName = productTypeName.replace(/<[^>]*>/g, "");
          var option = "<option selected>" + productTypeName + "</option>";
          console.log(option);
          $("form select[name='productTypeId']").html(option);
          form.render("select");
          if (data && data.eventType == "addSpec") {
            data.sortNumber = "";
          }

          form.val("productSpecForm", data);
          form.render();

          var getTemplateHtml = function (i) {
            var labelName = "";
            var valLen = $("form input[name='quantity']").length;
            if (valLen == 0) {
              labelName = "规格值";
            }
            var templateHtml =
              "" +
              '<div class="layui-form-item" >' +
              '<div class="layui-form-item">' +
              "<div >" +
              '<label class="layui-form-label" >' +
              labelName +
              "</label>" +
              '<div class="layui-input-inline">' +
              '<input id="value' +
              i +
              '" name="value" placeholder="请输规格值" type="text" class="layui-input" lay-verify="required" required/>' +
              "</div>" +
              "</div>" +
              "<div >" +
              '<div class="layui-input-inline">' +
              '<input id="sort' +
              i +
              '" name="sort" placeholder="排序值" type="text" class="layui-input" lay-verify="sortNumber" required/>' +
              "</div>" +
              "</div>";
            templateHtml +=
              '<div class="layui-input-inline">' +
              '<button id="btnDel' +
              i +
              '" class="layui-btn delBtn" lay-filter="btnDel' +
              i +
              '" style="margin-left: 20px;">删除</button>' +
              "</div>";
            templateHtml += "</div>" + "</div>";
            return templateHtml;
          };

          var i = 0;
          var btnCount = 0;
          var addTemplateDiv = function () {
            var html = getTemplateHtml(i++);
            $("#btnAddDiv").prev().after(html);
            form.render();
            form.render("select");
            $(".delBtn")
              .off("click")
              .on("click", function () {
                var btn = $(this);
                var btnId = btn[0].id;
                var btnNo = btnId.substring("btnDel".length, btnId.length);
                btn.parent().parent().parent().remove();
              });
          };

          $("#btnAdd").click(addTemplateDiv);

          if (data == undefined || (data && (data.eventType == "addSpec" || data.eventType == "addSpecFromSpecTable"))) {
            // addTemplateDiv();
            $("#btnAdd").hide();
            $("#btnDel0").hide();
          }
          form.on("select(style)", function (data) {
            if (data.value == "text") {
              $("#btnAdd").hide();
              $(".attributeDiv").remove();
            } else if (data.value == "single") {
              $("#btnAdd").show();
              if ($("form input[name='value']").length == 0) {
                addTemplateDiv();
                $("#btnDel0").hide();
              }
            }
          });
          if (data && data.eventType == "editSpec") {
            if (data.style === "text") {
              $("#btnAdd").hide();
            }
            if (data.style === "single") {
              admin.req(
                "enterprise/product/admin/productSpecValue/list",
                {
                  productSpecId: data.id,
                  limit: 9999
                },
                function (res) {
                  if (res.code == 200) {
                    for (var k = 0; k < res.data.length; k++) {
                      addTemplateDiv();
                      $("#btnDel0").hide();
                      var elementNo = i - 1;
                      var value = res.data[k].value;
                      var sortNumber = res.data[k].sortNumber;
                      $("#value" + elementNo).val(value);
                      $("#sort" + elementNo).val(sortNumber);
                      form.render();
                    }
                  } else {
                    layer.msg("获取规格值失败", { icon: 2, time: 1000 });
                  }
                },
                "GET"
              );
            }
          }

          // 表单提交事件
          form.on("submit(productSpecFormSubmit)", function (d) {
            layer.load(2);
            var detailList = [];
            var vals = [];
            var sorts = [];
            $("form input[name='value']").each(function (index, item) {
              var val = $(this).val();
              vals.push(val);
            });

            $("form input[name='sort']").each(function (index, item) {
              var val = $(this).val();
              sorts.push(val);
            });

            for (var k = 0; k < vals.length; k++) {
              var obj = { value: vals[k], sortNumber: sorts[k] };
              detailList.push(obj);
            }
            if (data && (data.eventType == "addSpec" || data.eventType == "addSpecFromSpecTable")) {
              d.field.id = undefined;
              d.field.productType = data.id;
            } else {
              d.field.productType = data.productType;
            }
            d.field.name = d.field.specName;
            d.field.detailList = detailList;
            admin.req(
              data && (data.eventType == "addSpec" || data.eventType == "addSpecFromSpecTable")
                ? "enterprise/product/admin/productSpec/add"
                : "enterprise/product/admin/productSpec/update",
              JSON.stringify(d.field),
              function (res) {
                layer.closeAll("loading");
                if (res.code == 200) {
                  layer.msg(res.msg, { icon: 1 });
                  if (data && (data.eventType == "addSpecFromSpecTable" || data.eventType == "editSpec")) {
                    table.reload("productSpecTable");
                    layer.close(openIndex);
                  } else {
                    layer.closeAll("page");
                  }
                } else {
                  layer.msg(res.msg, { icon: 2 });
                }
              },
              "POST",
              true,
              "application/json; charset=utf-8"
            );
            return false;
          });
        }
      });
    }
  });
</script>
